//
//  SearchMapViewController.m
//  StationManager
//
//  Created by 泽华伟业 on 17/3/18.
//  Copyright © 2017年 Helong. All rights reserved.
//

#import "SearchMapViewController.h"
#import <BaiduMapKit/BaiduMapAPI_Search/BMKPoiSearch.h>
#import <BaiduMapKit/BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapKit/BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "SearchResultTableViewCell.h"
#import "STMPointAnnotation.h"
#import "STMPinAnnotationView.h"
#import "SearchBottomView.h"
#import "SearchFootView.h"

@interface SearchMapViewController ()<BMKPoiSearchDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,UITableViewDelegate,UITableViewDataSource>
//搜索界面传过来的搜索关键词
@property (nonatomic,copy) NSString *keyWord;
//检索对象
@property (nonatomic,strong) BMKPoiSearch *searcher;
//地图
@property (nonatomic,strong) BMKMapView* mapView;
//定位
@property (nonatomic,strong) BMKLocationService *locService;
//检索结果数组
@property (nonatomic,strong) NSMutableArray *eachPageArray;
//列表
@property (nonatomic,strong) UITableView *tableView;
//底部视图
@property (nonatomic,strong) SearchBottomView *bottomView;
//标注数组
@property (nonatomic,strong) NSMutableArray *annotationArray;

@property (nonatomic,assign) int page;
//总页数
@property (nonatomic,assign) int allPage;
//显示搜索结果总数
@property (nonatomic,strong) UILabel *titleLabel;
@end

@implementation SearchMapViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _mapView.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _searcher.delegate = nil;
    _mapView.delegate = nil;
}

- (instancetype)initWithKeyWord:(NSString *)keyWord
{
    self = [super init];
    if (self) {
        self.keyWord = [NSString stringWithString:keyWord];
    }
    return self;
}

- (UILabel *)titleLabel{
    if (!_titleLabel ) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        self.navigationItem.titleView = _titleLabel;
        [_titleLabel setFont:TEXT_FONT];
        [_titleLabel  setTextAlignment:NSTextAlignmentCenter];
    }
    return _titleLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //_eachPageArray = [NSMutableArray array];
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    //显示比例尺
    _mapView.showMapScaleBar = YES;
    _mapView.zoomLevel = 16;
    _mapView.centerCoordinate = _location;
    [self.view addSubview:_mapView];
    _annotationArray  = [NSMutableArray array];
    //定位
    [self locationOnMap];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //检索
    [self setPoiSearchWithPage:0];
    _page = 0;
   //添加列表按钮
    [self addRightNavigationItem];
    //添加列表
    [self addTableVIew];
}

#pragma  mark -- 底部视图
- (void)addBottomViewWithPoiInfo:(BMKPoiInfo *)info {
    if (!_bottomView) {
        _bottomView = [[SearchBottomView alloc]init];
        _bottomView.poiInfo = info;
        _bottomView.location = _location;
        [self.view addSubview:_bottomView];
        [_bottomView setTextForlabelWithName:info.name Address:info.address];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(120*hl);
        }];
    }
}
// 重新设置底部视图位置
- (void)remakeBottomViewLocationByBottomDistance:(int)bottomDistance{
    [_bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(bottomDistance);
        make.height.mas_equalTo(120*hl);
    }];
}
//定位
- (void)locationOnMap{
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    // _locService.userLocation
    [_locService startUserLocationService];
    //以下_mapView为BMKMapView对象
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
}

//检索
- (void)setPoiSearchWithPage:(int)page{
    _searcher = [[BMKPoiSearch alloc]init];
    _searcher.delegate = self;
    //发起检索（周边搜索）
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
    option.pageIndex = page;
    option.pageCapacity = 15;
    //排序书序    综合排:BMK_POI_SORT_BY_COMPOSITE = 0,距离由近到远排序BMK_POI_SORT_BY_DISTANCE,//
    //option.sortType = BMK_POI_SORT_BY_DISTANCE;
    option.keyword =  _keyWord;
    option.location = _location;
    //半径
    option.radius = 2000;
    BOOL flag = [_searcher poiSearchNearBy:option];
    if (flag) {
        HLog(@"检索成功");
    }else{
        HLog(@"检索失败");
    }
}

//添加右上角的列表按钮
- (void)addRightNavigationItem{
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"列表" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemDidSelected:)];
    self.navigationItem.rightBarButtonItem = rightItem;
}
//rightButtonItem点击方法
- (void)rightItemDidSelected:(UIBarButtonItem *)item{
    if ([item.title isEqualToString:@"列表"]) {
        [item setTitle:@"地图"];
        [self remakeTableViewTopWithOffset:0];
        [self remakeBottomViewLocationByBottomDistance:120*hl];
     }else if ([item.title isEqualToString:@"地图"]){
         [item setTitle:@"列表"];
         //回收列表。弹出底部视图
         [self remakeTableViewTopWithOffset:SCREEN_HEIGHT];
         [self remakeBottomViewLocationByBottomDistance:0];
    }
}

- (void)remakeTableViewTopWithOffset:(int)offset{
   [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
       make.left.right.equalTo(self.view);
       make.top.equalTo(self.view).offset(offset);
       make.height.mas_equalTo(SCREEN_HEIGHT - 64);
   }];
}

- (void)addTableVIew{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(SCREEN_HEIGHT);
        make.height.mas_equalTo(SCREEN_HEIGHT - 64);
    }];
}

#pragma mark -- 检索代理方法
//实现代理回调
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        //在此处理正常结果
        HLog(@"%@",poiResult);
        //获取总数 计算出页数
        [self.titleLabel setText:[NSString stringWithFormat:@"共搜索到%d条关于\"%@\"的结果",poiResult.totalPoiNum,_keyWord]];
        _allPage = (poiResult.totalPoiNum / 15) + 1 ;
        _eachPageArray = [NSMutableArray arrayWithArray:poiResult.poiInfoList];
        [_tableView reloadData];
        [self AddAnnotationViewsOnMapWithArray:_eachPageArray];
        //添加底部视图
        BMKPoiInfo *info = [_eachPageArray objectAtIndex:0];
        [self addBottomViewWithPoiInfo:info ];
    }
    else if (errorCode == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
    } else {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark -- 通过数组添加标注
- (void)AddAnnotationViewsOnMapWithArray:(NSArray *)infoArray{
    //添加前先移除以前的
    [_mapView removeAnnotations:_annotationArray];
    [_annotationArray removeAllObjects];
    for (BMKPoiInfo *info in infoArray) {
        STMPointAnnotation *annotation = [[STMPointAnnotation alloc]init];
        annotation.coordinate = info.pt;
        annotation.title = info.name;
        //将info赋值给标注
        annotation.info = info;
        [_annotationArray addObject:annotation];
    }
    [_mapView addAnnotations:_annotationArray];
}

#pragma mark -- mapView代理方法
//添加标注
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    ///STMPointAnnotation 继承于BMKAnnotation 添加一个是否有故障的标记isBad
    STMPointAnnotation *searAnnotation = (STMPointAnnotation *)annotation;
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        STMPinAnnotationView *newAnnotationView = [[STMPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        //站点标注赋值
        [newAnnotationView.nameLbel setText:annotation.title];
        //将标注中的info传给标注视图作为属性
        newAnnotationView.info = searAnnotation.info;
        return newAnnotationView;
    }
    return nil;
}
//点击大头针
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    STMPinAnnotationView *searchAnnotationView = (STMPinAnnotationView *)view;
    //底部视图重新赋值
    _bottomView.poiInfo = searchAnnotationView.info;
    [_bottomView setTextForlabelWithName:searchAnnotationView.info.name Address:searchAnnotationView.info.address];
}

#pragma mark -- tableView 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _eachPageArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchMapTableViewCell"];
    if (!cell) {
        cell = [[SearchResultTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchMapTableViewCell"];
    }
    BMKPoiInfo *info  = [_eachPageArray objectAtIndex:indexPath.row];
    //赋值
    [cell setTextForLabelWithName:info.name Address:info.address];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击tableView 地图滚动到指定位置
    BMKPoiInfo *info = [_eachPageArray objectAtIndex:indexPath.row];
    _mapView.centerCoordinate = info.pt;
    self.navigationItem.rightBarButtonItem.title = @"列表";
    //回收列表，弹出底部视图
    [self remakeTableViewTopWithOffset:SCREEN_HEIGHT];
    [self remakeBottomViewLocationByBottomDistance:0];
    _mapView.zoomLevel = 20;
    [_bottomView setTextForlabelWithName:info.name Address:info.address];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40*hl;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    SearchFootView *footView = [[SearchFootView alloc]init];
    footView.backgroundColor = [UIColor lightGrayColor];
    [footView.pageLable setText:[NSString stringWithFormat:@"%d/%d",(_page +1),_allPage]];
    footView.buttonSelectedBlock = ^(NSString *buttonTitle){
        if ([buttonTitle isEqualToString:@"上一页"]) {
        _page = _page -1;
        [self setPoiSearchWithPage:_page];
        }else if ([buttonTitle isEqualToString:@"下一页"])
        _page = _page +1;
        [self setPoiSearchWithPage:_page];
    };
    return footView;
}


#pragma mark -- 定位代理方法
/**
 *在将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser{

}

/**
 *在停止定位后，会调用此函数
 */
- (void)didStopLocatingUser{

}

//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"heading is %@",userLocation.heading);
    [_mapView updateLocationData:userLocation];
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//    _userLatitude = userLocation.location.coordinate.latitude;
//    _userLongitude = userLocation.location.coordinate.longitude;
    [_mapView updateLocationData:userLocation];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
